<template>
  <div class="detection-plan-list-page">        
    <div class="card-stack">
      <el-card class="card-block breadcrumb-card">
        <el-breadcrumb :separator-icon="ArrowRight">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>质量管理</el-breadcrumb-item>
          <el-breadcrumb-item>检测管理</el-breadcrumb-item>
          <el-breadcrumb-item>质检方案</el-breadcrumb-item>
        </el-breadcrumb>
      </el-card>
      <el-card class="card-block query-card">
        <el-form class="filter-form" :inline="true" :model="queryForm" label-width="auto">
          <el-form-item label="质检方案">
            <el-input
              v-model="queryForm.keyword"
              placeholder="请输入质检方案编号/名称"
              clearable
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="queryForm.planstate" placeholder="请选择状态" clearable style="width: 180px">
              <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
      <el-card class="card-block table-card">
        <div class="table-toolbar">
          <div>
            <el-button type="primary" @click="handleAdd">新增</el-button>
            <el-button type="danger" plain :disabled="!multipleSelection.length" @click="handleBatchDelete">
              删除
            </el-button>
          </div>
          <div class="table-total">共 {{ pagination.totalCount }} 条</div>
        </div>
        <el-table
          :data="tableData"
          border
          stripe
          style="width: 100%"
          :loading="loading"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="index" label="序号" width="70" />
          <el-table-column prop="planname" label="质检方案名称" min-width="160" />
          <el-table-column prop="plancode" label="质检方案编号" min-width="140" />
          <el-table-column prop="detectioncategory" label="检测分类" min-width="120">
            <template #default="{ row }">
              {{ row.detectioncategory === "物料检测" ? "物料" : "产品" }}
            </template>
          </el-table-column>
          <el-table-column prop="inspectiontype" label="检测种类" min-width="200">
            <template #default="{ row }">
              {{ formatInspectionType(row.inspectiontype) }}
            </template>
          </el-table-column>
          <el-table-column label="状态" width="110">
            <template #default="{ row }">
              <el-tag :type="row.planstate === '启用' ? 'success' : 'info'">
                {{ row.planstate }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="plandes" label="备注" min-width="160" show-overflow-tooltip />
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" link size="small" @click="handleEdit(row)">编辑</el-button>
              <el-button type="danger" link size="small" @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            v-model:current-page="pagination.pageIndex"
            v-model:page-size="pagination.pageSize"
            :total="pagination.totalCount"
            :page-sizes="[10, 20, 30, 50]"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ArrowRight } from "@element-plus/icons-vue";
import { reactive, ref, onMounted, onActivated } from "vue";
import { useRouter } from "vue-router";
import https from "@/Http/http";
import { ElMessage, ElMessageBox, type FormInstance } from "element-plus";

type ApiEnum = -1 | 0 | 1;

interface ApiPageingResponse<T> {
  code: ApiEnum;
  msg: string;
  data: T[];
  totalCount: number;
  pageCount: number;
}

interface ApiResultResponse<T> {
  code: ApiEnum;
  msg: string;
  data: T;
}

interface DetectionPlanDTO {
  id: number;
  plancode: string;
  planname: string;
  detectioncategory: string;
  inspectiontype: string;
  planstate: string;
  plandes?: string;
}

interface DetectionPlanRow extends DetectionPlanDTO {
  index: number;
}

const router = useRouter();
const loading = ref(false);
const tableData = ref<DetectionPlanRow[]>([]);
const multipleSelection = ref<DetectionPlanRow[]>([]);

const statusOptions = [
  { label: "启用", value: "启用" },
  { label: "禁用", value: "禁用" },
];

const queryForm = reactive({
  keyword: "",
  planstate: "",
});

const pagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0,
});

// 格式化检测种类显示
const formatInspectionType = (types: string) => {
  if (!types) return "-";
  return types;
};

const fetchTableData = async () => {
  loading.value = true;
  try {
    const params: Record<string, any> = {
      pagesize: pagination.pageSize,
      pageindex: pagination.pageIndex,
    };
    
    // 处理关键词搜索（编号或名称）
    if (queryForm.keyword) {
      params.keyword = queryForm.keyword;
    }
    
    // 状态筛选
    if (queryForm.planstate) {
      params.planstate = queryForm.planstate;
    }

    const response = await https.Reads.get<ApiPageingResponse<DetectionPlanDTO>>(
      "/Detection/DetectionPlanList",
      { params }
    );
    
    const data = response.data;
    
    if (data.code !== 1) {
      throw new Error(data.msg || "查询失败");
    }
    
    pagination.totalCount = data.totalCount || 0;
    tableData.value = (data.data || []).map((item, index) => ({
      ...item,
      index: (pagination.pageIndex - 1) * pagination.pageSize + index + 1,
    }));
  } catch (error: any) {
    console.error("获取质检方案列表失败:", error);
    if (error.response?.status === 404) {
      ElMessage.error("接口不存在，请确认后端服务已正确启动并重新编译");
    } else {
      ElMessage.error(error.message || "获取质检方案列表失败");
    }
  } finally {
    loading.value = false;
  }
};

const handleQuery = () => {
  pagination.pageIndex = 1;
  fetchTableData();
};

const handleReset = () => {
  queryForm.keyword = "";
  queryForm.planstate = "";
  handleQuery();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  fetchTableData();
};

const handleCurrentChange = (page: number) => {
  pagination.pageIndex = page;
  fetchTableData();
};

const handleSelectionChange = (rows: DetectionPlanRow[]) => {
  multipleSelection.value = rows;
};

const handleAdd = () => {
  router.push("/DetectionPlanAdd");
};

const handleEdit = (row: DetectionPlanDTO) => {
  // 编辑功能：可以跳转到编辑页面，或者打开弹框
  // 这里假设有编辑页面，如果没有可以改为弹框编辑
  router.push({
    path: "/DetectionPlanAdd",
    query: {
      id: row.id.toString(),
    },
  });
};

const deleteDetectionPlan = (id: number) =>
  https.Writes.request<ApiResultResponse<number>>({
    method: "delete",
    url: "/Detection/DetectionPlanDel",
    params: { id },
  });

const handleDelete = (row: DetectionPlanRow) => {
  ElMessageBox.confirm(`确认删除质检方案【${row.planname}】吗？`, "提示", {
    type: "warning",
  })
    .then(async () => {
      try {
        const res = await deleteDetectionPlan(row.id);
        if (res.data.code !== 1) {
          throw new Error(res.data.msg || "删除失败");
        }
        ElMessage.success("删除成功");
        fetchTableData();
      } catch (error: any) {
        console.error(error);
        ElMessage.error(error.message || "删除失败");
      }
    })
    .catch(() => {});
};

const handleBatchDelete = () => {
  if (!multipleSelection.value.length) return;
  ElMessageBox.confirm(`确认删除选中的 ${multipleSelection.value.length} 条数据吗？`, "提示", {
    type: "warning",
  })
    .then(async () => {
      try {
        await Promise.all(
          multipleSelection.value.map((item) => deleteDetectionPlan(item.id)),
        );
        ElMessage.success("批量删除成功");
        fetchTableData();
      } catch (error: any) {
        console.error(error);
        ElMessage.error(error.message || "批量删除失败");
      }
    })
    .catch(() => {});
};

// 检查是否从新增页面返回并刷新列表
const checkAndRefresh = () => {
  const fromAdd = sessionStorage.getItem("fromDetectionPlanAdd");
  if (fromAdd === "true") {
    sessionStorage.removeItem("fromDetectionPlanAdd");
  }
  fetchTableData();
};

onMounted(() => {
  fetchTableData();
});

// 监听路由激活，如果从新增页面返回，刷新列表
onActivated(() => {
  checkAndRefresh();
});
</script>

<style scoped>
.detection-plan-list-page {
  min-height: calc(100vh - 60px);
  padding: 16px;
  background: linear-gradient(135deg, #f3f5ff 0%, #fef5f5 45%, #fdf8ff 100%);
}

.card-stack {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.card-block {
  width: 100%;
  background: linear-gradient(145deg, rgba(255, 255, 255, 0.85), rgba(242, 248, 255, 0.78));
  border: 1px solid rgba(255, 255, 255, 0.6);
  box-shadow: 0 10px 30px rgba(15, 36, 70, 0.08);
  backdrop-filter: blur(12px);
  border-radius: 12px;
}

.query-card,
.table-card {
  width: 100%;
}

.filter-form :deep(.el-form-item) {
  margin-bottom: 12px;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.table-total {
  color: #909399;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  padding-top: 16px;
}
</style>

